package demo2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode15 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        int n = nums.length - 1;
        for (int k = 0; k <= n - 2; ) {
            int left = k + 1, right = n;
            int target = -nums[k];
            while (left < right) {
                if (nums[left] + nums[right] < target) left++;
                else if (nums[left] + nums[right] > target) right--;
                else {
                    list.add(new ArrayList<Integer>(Arrays.asList(nums[k], nums[left], nums[right])));
                    left++; right--;
                    while(left < right && nums[left] == nums[left - 1]) left++;
                    while(left < right && nums[right] == nums[right + 1]) right--;
                }
            }
            k++;
            while (k <= n - 2 && nums[k] == nums[k - 1]) k++;
        }
        return list;
    }
}
